package com.example.learndemo.dataAlgorithm;

public class ArrayOperate  {
	private int size;
	private int[] data;
	private int index;
	private int count=0;

	public ArrayOperate() {
		this.size = 16;
		this.data = new int[0];
		this.index = 0;
	}

	public void add(int item) {
		checkExpanded();
		data[index] = item;
		index++;
	}

	public void print() {
		for (int i = 0; i < data.length; i++) {
			System.out.println(i + ":" + data[i]);
		}
		System.out.println("-------------------------------");
	}

	private void checkExpanded() {
		if (index < size) {
			return;
		}
        System.out.println("我要扩容了=========="+count++);
		size = size * 2;
		int[] dest = new int[size];
		System.arraycopy(data, 0, dest, 0, index);
		data = dest;
	}

	public void set(int idx, int item) {
		if (idx >= index) {
			throw new IndexOutOfBoundsException("数组越界了，一会再优化一下");
		}
		checkExpanded();
		for (int i = index; i > idx; i--) {
			data[i] = data[i - 1];
		}
		data[idx] = item;
		index++;
	}

	public static void main(String[] args) {
		ArrayOperate arr = new ArrayOperate();
		for (int i = 0; i < 1000000; i++) {
			arr.add(i);
		}
//		arr.print();
        arr.set(9,100);
//		arr.print();
	}
}
